﻿use std::{env, process};
use std::error::Error;
use crate::scoop_app::Scoop;
use crate::bucket::Bucket;
use crate::search_app::SearchApp;
pub struct Args {
    pub query: String,
}

pub fn parse_args(args: env::Args) -> Result<Args, Box<dyn Error>> {
    let args: Vec<String> = args.collect();
    let query: String;
    if let  1  = args.len() {
        query = String::new();
    } else if let  2   = args.len() {
        query = args[1].clone();
    } else {
        return Err(Box::from("args number incorrect."));
    }
    Ok(Args {
        query: query.to_lowercase(),

    })
}


fn search_exclude_bin(scoop: &Scoop, query: &str) -> Result<(), Box<dyn Error>> {
    let bucket_paths = Bucket::get_bucket_paths(scoop);

    match Bucket::search_exclude_bin(&bucket_paths, query) {
        Some(buckets) =>  {display_buckets(&buckets)  ;process::exit(0);}
        None => {
            println!("No apps found matching '{}'", query);
        }
    }
    Ok(())
}

pub fn run(scoop: &Scoop, args: &Args) -> Result<(), Box<dyn Error>> {
    search_exclude_bin(scoop, &args.query)  // 默认不包含二进制

}


pub fn display_apps(bucket_name: &str, apps: &Vec<SearchApp>) {
    if !apps.is_empty() {
        println!("'{}' bucket: ", bucket_name, );
        for app in apps {
            if app.version != "" {
                if !app.bin.is_empty() {
                    println!(
                        "    {} ({}) --> includes '{}'",
                        app.name, app.version, app.bin[0]
                    );
                } else {
                    println!("    {} ({})", app.name, app.version);
                }
            } else {
                println!("    {}", app.name);
            }
        }
        println!();
    }
}

pub fn display_buckets(buckets: &Vec<Bucket>) {
    for bucket in buckets {
        display_apps(&bucket.name, &bucket.apps);

    }
    process::exit(0);
}

